import 'package:common_utils/common_utils.dart';
import 'package:flutter_demo/tmac/util/AndroidFlutterPlugin.dart';
import 'package:geolocator/geolocator.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

class HttpUtil {
  double latitude;
  double longitude;
  Geolocator geolocator;
  String openWeatherMapURL = 'http://v.juhe.cn/weather/geo';
  String openCityWeatherMapURL = 'http://v.juhe.cn/weather/index';
  String apiKey = '0ca92484d26657567ffaf07472e1d075';

  factory HttpUtil() => _getInstance();

  static HttpUtil get instance => _getInstance();

  static HttpUtil _instance;

  HttpUtil._internal() {}

  static HttpUtil _getInstance() {
    if (_instance == null) {
      _instance = new HttpUtil._internal();
    }
    return _instance;
  }

  Future<dynamic> getCityWeather() async {
    Geolocator geolocator = Geolocator()..forceAndroidLocationManager;

    bool isOpenGps = await geolocator.isLocationServiceEnabled();
    if(!isOpenGps){
      AndroidFlutterPlugin.instance.showShortToast("请手动打开gps设置");
    }

    Position position = await geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.best);

    var weather = httpGet(
        '$openWeatherMapURL?format=2&key=$apiKey&dtype=json&lat=${position.latitude}&lon=${position.longitude}');
    return weather;
  }

  Future<dynamic> httpGet(String url) async {
    try {
      http.Response response = await http.get(url);
      LogUtil.v("url $url");
      if (response.statusCode == 200) {
        String data = response.body;
        LogUtil.v("获取到的数据 $data");

        return jsonDecode(data);
      } else {
        print(response.statusCode);
      }
    } catch (e) {
      print(e);
    }
  }

  Future<dynamic> httpPost(String url, Map<String, dynamic> param) async {
    try {
      http.Response response =
          await http.post(url, body: jsonEncode(param), encoding: Utf8Codec());
      if (response.statusCode == 200) {
        String data = response.body;
        return jsonDecode(data);
      } else {
        print(response.statusCode);
      }
    } catch (e) {
      print(e);
    }
  }

// void addProduct(Product product) async {
//   Map<String, dynamic> param = {
//     'title': product.title,
//     'description': product.description,
//     'price': product.price
//   };
//   try {
//     final http.Response response = await http.post(
//         'https://flutter-cn.firebaseio.com/products.json',
//         body: json.encode(param),
//         encoding: Utf8Codec());
//
//     final Map<String, dynamic> responseData = json.decode(response.body);
//     print('$responseData 数据');
//
//   } catch (error) {
//     print('$error错误');
//   }
// }
}
